import { nanoid } from 'nanoid'

/**
 * 在地图上渲染DOM节点
 * @param {Earth} options.earth 渲染容器
 * @param {Array} options.position 节点所在GIS位置 [ lng, lat, h ]
 * @param {String} options.divStr dom节点字符串
 * @param {Array} options.offset 与坐标点的偏移量 单位像素
 * 
 * @methods destroy 销毁
 * @methods setShow 设置dom显示
 * 
 * @returns {DrawPinDiv} DrawPinDiv实例
 */
function DrawPinDiv (options) {

    this.type = 'DrawPinDiv'
    let radian = Math.PI / 180;
    let earth = options.earth
    let divStr = options.divStr
    let offset = options.offset || [ 0, 0 ]
    let divId = nanoid(5)
    let that = this
    

    const evalString = `
        if (p._div) {
            return;
        }

        const earth = p.earth;

        // 创建div
        const div = document.createElement('div');
        div.id = '${ divId }'
        div.style.cssText = \`
            position: absolute;
        \`;
        div.innerHTML = '${ divStr || "" }'
        // div.onclick = () => {
        //     console.log('即将飞入div坐标点');
        //     const position = [1.901729390218574, 0.5972202012953493, 594.3184362850787];
        //     const rotation = [5.538756509291041, -0.5562768563795704, 6.280692859184528];
        //     earth.camera.flyTo(position, 0, rotation);
        // };
        const container = earth.czm.viewer.container;
        container.appendChild(div);
        p._div = div;

        // 自动删除div
        // disposers数组会在p销毁时执行，从而销毁Pin所附带的资源，避免内存泄露
        p.disposers.push(() => {
            container.removeChild(div);
            p._div = undefined;
        });

        // 动态修改div的位置
        p.disposers.push(XE.MVVM.watch(() => [...p.winPos], () => {
            div.style.left = (p.winPos[0] + ${ offset[0] }) + 'px';
            div.style.bottom = (p.winPos[3] + ${ offset[1] }) + 'px';
        }));
    `;


    let position = [ options.position[0] * radian, options.position[1] * radian, options.position[2] || 0 ]

    const objConfig = {
        "xbsjType": "Pin",
        "position": position,
        "show": false,
        evalString
    };
    const pin = new XE.Obj.Pin(earth);
    pin.xbsjFromJSON(objConfig);

    this.XEObj = pin
    this.divId = divId
    this.data = options.data || null

    document.getElementById(this.divId).onclick = function () {
        that.click()
    }

}

DrawPinDiv.prototype.click = function () {
    if (this.onclick) { this.onclick() }
}

DrawPinDiv.prototype.destroy = function () {
    this.XEObj.destroy()
}

DrawPinDiv.prototype.setShow = function (options) {
    document.getElementById(this.divId).style.display = options ? 'block' : 'none'
}



export default DrawPinDiv